let app = getApp();
// let compose = require('../../utils/compose');
// var util = require('../../utils/util.js');
var applet_park_api_url = app.globalData.applet_park_api_url;
var applet_park_api_url_imgUrl = app.globalData.applet_park_api_url_imgUrl;
var util = require('../../../utils/util.js');
const {
  ymdFormat
} = require('../../../utils/util.js');
const {
  requestDataparams
} = require('../../../utils/request.js');
Page({
  data: {
    imgUrl: applet_park_api_url_imgUrl,
    roomId: '',
    dateCurrentStr: ymdFormat(new Date()), // 正选择日期的 id
    bgWhiteImgUrl: 'http://img0.imgtn.bdimg.com/it/u=1641805254,627977274&fm=26&gp=0.jpg', //选中的日期白色背景图
    Dates: [],
    dateListArray: ['周 日', '周 一', '周 二', '周 三', '周 四', '周 五', '周 六'],
    maxCount: 15, //横向日期默认显示的日期数量
    clientHeight: 0,
    clientWidthCount: 0,
    hasEmptyGrid: false,
    cur_year: '',
    cur_month: '',
    showModal: false,
    showModal2: false,
    listbuild: ['请选择'],
    listbuildid: [null],
    floorId: '',
    buildid: '',
    listbuildindex: 0,
    listfloor: ['请选择'],
    listfloorid: [],
    listfloorindex: 0,
    items: [],
    roomsNum: 0,
    conferenceDeviceList: [],
    detail: {

    },
    capacity: '',
  },
  dateSelectAction: function (e) { //切换日期
    var cur_day = e.currentTarget.dataset.idx;
    this.setData({
      todayIndex: cur_day
    })
    let day = parseInt(cur_day) + 1;
    let time = this.data.cur_year + '-' + this.data.cur_month + '-' + day

    this.setData({
      dateCurrentStr: time,
      showModal: false,
    });
    this.loadDatameetinglist();
  },
  formatTimehour: function (date) {

    let hour = date.substring(0, 2).replace(/\b(0+)/gi, "");
    return hour
  },
  setNowDate: function () { //设置当前周几
    const openid = wx.getStorageInfoSync("OPENID");
    const date = new Date();
    const cur_year = date.getFullYear();
    const cur_month = date.getMonth() + 1;
    const todayIndex = date.getDate() - 1;
    const weeks_ch = ['日', '一', '二', '三', '四', '五', '六'];
    this.calculateEmptyGrids(cur_year, cur_month);
    this.calculateDays(cur_year, cur_month);
    this.setData({
      cur_year: cur_year,
      cur_month: cur_month,
      weeks_ch,
      todayIndex,
    })
  },

  getThisMonthDays(year, month) {
    return new Date(year, month, 0).getDate();
  },
  getFirstDayOfWeek(year, month) {
    return new Date(Date.UTC(year, month - 1, 1)).getDay();
  },
  calculateEmptyGrids(year, month) {
    const firstDayOfWeek = this.getFirstDayOfWeek(year, month);
    let empytGrids = [];
    if (firstDayOfWeek > 0) {
      for (let i = 0; i < firstDayOfWeek; i++) {
        empytGrids.push(i);
      }
      this.setData({
        hasEmptyGrid: true,
        empytGrids
      });
    } else {
      this.setData({
        hasEmptyGrid: false,
        empytGrids: []
      });
    }
  },
  calculateDays(year, month) {
    let days = [];
    const thisMonthDays = this.getThisMonthDays(year, month);
    for (let i = 1; i <= thisMonthDays; i++) {
      days.push(i);
    }
    this.setData({
      days
    });
  },
  handleCalendar(e) {
    const handle = e.currentTarget.dataset.handle;
    const cur_year = this.data.cur_year;
    const cur_month = this.data.cur_month;
    if (handle === 'prev') {
      let newMonth = cur_month - 1;
      let newYear = cur_year;
      if (newMonth < 1) {
        newYear = cur_year - 1;
        newMonth = 12;
      }

      this.calculateDays(newYear, newMonth);
      this.calculateEmptyGrids(newYear, newMonth);
      this.setData({
        cur_year: newYear,
        cur_month: newMonth
      })

    } else {
      let newMonth = cur_month + 1;
      let newYear = cur_year;
      if (newMonth > 12) {
        newYear = cur_year + 1;
        newMonth = 1;
      }

      this.calculateDays(newYear, newMonth);
      this.calculateEmptyGrids(newYear, newMonth);

      this.setData({
        cur_year: newYear,
        cur_month: newMonth
      })
    }
  },

  onLoad: function () {
    this.setNowDate();
    //加载前设置loading为true
    var that = this;
    wx.getSystemInfo({
      success: function (res) {
        that.setData({
          clientHeight: res.windowHeight - 90,
          clientWidthCount: parseInt(res.windowWidth / 50) ///一个小正方形宽度50，获得屏幕宽度计算数量
        });
      }
    })
    this.add(new Date(), "今 天"); //获取15天日期
    for (var i = 1; i <= this.data.maxCount; i++) {
      //获取AddDayCount天后的日期
      var txt = "";
      if (i == 1) {
        txt = "明 天"
      }
      if (i == 2) {
        txt = "后 天"
      }
      this.add(new Date().setDate(new Date().getDate() + i), txt);
    }
    this.setData({
      loading: true,
      Dates: this.data.Dates
    });
    var obj = this.data.Dates[0];
    this.ckeckDate(obj.id); //设置默认当前日期选中
    this.loadbuild();
    this.loadDatameetinglist(); //初始化加载数据
  },
  changeCapacity(e) { //可容纳人数
    // return
    let value = e.detail.value
    // value.test()
    let rxp = new RegExp("^[0-9]*$")
    let m = rxp.test(value)
    if (!m) {
      wx.showToast({
        title: '请输入数字',
        icon: 'none'
      })
      this.setData({
        capacity: ''
      })
      return
    }
    this.setData({
      capacity: value
    })
    this.loadDatameetinglist()
  },
  // 日历组件部分
  add: function (obj, txt) {
    var date = new Date(obj);
    var year = date.getFullYear();
    var mon = (date.getMonth() + 1) < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1;
    var day = date.getDate() < 10 ? '0' + date.getDate() : date.getDate();
    var week = this.data.dateListArray[date.getDay()];
    if (txt != "") {
      week = txt;
    }
    var obj = {
      id: year + '-' + mon + '-' + day,
      text: week,
      mon: mon,
      day: day,
    };
    this.data.Dates.push(obj);
  },
  ClickDateCheng: function (e) { //切换日期
    var currentDate = e.currentTarget.id;
    this.ckeckDate(currentDate);
  },
  ckeckDate(currentDate) { //切换日期
    this.setData({
      dateCurrentStr: currentDate
    });
    // 刷新列表
    wx.showToast({
      title: '加载中...',
      icon: 'loading',
      duration: 1000
    })
    this.loadDatameetinglist();
  },
  // 日历选择
  selectclor: function (e) {
    let that = this;
    this.setData({
      showModal: !that.data.showModal,
    })
  },
  //获取楼层 楼栋
  loadbuild() {
    var that = this;
    wx.request({
      url: applet_park_api_url + '/api/buildings',
      method: 'GET',
      header: {
        'content-type': 'application/x-www-form-urlencoded',
      },
      success(res) {
        let listbuild = [];
        listbuild.push("请选择楼栋")
        let listbuildid = [];
        listbuildid.push("null")
        if (res.data.code == 0) {
          for (let item of res.data.data) {
            listbuild.push(item.name)
            listbuildid.push(item.id)
          }
          that.data.listbuild = listbuild;
          that.data.listbuildid = listbuildid;
          that.setData(that.data);
        } else {
          wx.showToast({
            title: '网络异常',
          })
        }
      },
      fail(res) {
        wx.showToast({
          title: res.data,
        })
      }
    })
  },
  //获取楼栋
  loadFloor() {
    var that = this;
    if(that.data.buildid=="null"){
      that.setData({
        buildid: 0
      })
    }
    wx.request({
      url: applet_park_api_url + '/api/floors?buildingId=' + that.data.buildid,
      success(res) {
        let listfloor = [];
        listfloor.push("请选择房楼层")
        let listfloorid = [];
        listfloorid.push("null")
        if (res.data.code == 0) {
          for (let item of res.data.data) {
            listfloor.push(item.name)
            listfloorid.push(item.id)
          }
          that.data.listfloor = listfloor;
          that.data.listfloorid = listfloorid;
          that.setData(that.data);
        } else {
          wx.showToast({
            title: res.data.mesage,
          })
        }
      },
      fail(res) {
        wx.showToast({
          title: res.data.message
        })
      }
    })
    that.loadDatameetinglist();
  },
  bindKeyInput: function (e) {
    this.data[e.currentTarget.dataset.inputname] = e.detail.value;
    this.setData(this.data);
  },
  changebuild: function (e) { //切换楼栋
    this.data.buildid = this.data.listbuildid[e.detail.value];
    this.data.listbuildindex = e.detail.value;
    this.setData(this.data);
    this.loadFloor();
  },
  changefloor: function (e) { //切换楼层
    if (!this.data.buildid || this.data.buildid == 'null' || this.data.buildid == null) {
      util.showModal('请先选择楼栋');
      return
    }
    this.data.floorId = this.data.listfloorid[e.detail.value];
    this.data.listfloorindex = e.detail.value;
    this.setData(this.data);
    this.loadDatameetinglist()
  },
  loadDatameetinglist() { //获取列表数据
    var that = this;
    if (that.data.buildid == "null") {
      that.setData({
        buildid: ''
      })
    }
    if (that.data.floorId == "null") {
      that.setData({
        floorId: ''
      })
    }
    var data = {
      buildingId: that.data.buildid,
      floorId: that.data.floorId,
      day: that.data.dateCurrentStr + ' 00:00:00',
      capacity: that.data.capacity,
    };
    var url = applet_park_api_url_imgUrl;
    requestDataparams('/api/conferenceRooms', data, 'GET').then(res => {
      if (res.data.code == 0) {
        let items = [];
        var lists = res.data.data;
        for (let item of lists) {
          if (item.images) {
            item.images = url + '/' + (item.images).split(',')[0];
          }
          for (let tt of item.conferenceScheduleVOList) {
            tt.time = that.formatTimehour(tt.time);
          }
          items.push(item);
        }
        that.setData({
          items: items,
          roomsNum: items.length
        })

        if (that.data.items.length == 0) {
          that.setData({
            title: '暂无更多数据',
          })
        } else {
          that.setData({
            title: ''
          })
        }

      }
    }).catch(err => {

    });
  },
  meetingdetail(e) { //点击列表 获取数据 跳转页面
    let detail = {};
    var that = this;
    detail.meetingimg = e.currentTarget.dataset.meetingimg;
    detail.meetingname = e.currentTarget.dataset.meetingname;
    detail.price = e.currentTarget.dataset.price;
    detail.buildingname = e.currentTarget.dataset.buildingname;
    detail.devices = e.currentTarget.dataset.devices;
    that.setData({
      roomId: e.currentTarget.dataset.id,
      detail: detail
    });
    that.goMettingDetail();
  },
  closedetail() {
    this.setData({
      showModal2: false
    });
  },
  claseshowmo() {
    this.setData({
      showModal: false
    });
  },
  // 去预定界面
  goMettingDetail() {
    var that = this;
    var price = that.data.detail.price;
    wx.navigateTo({
      url: '../../../packageA/pages/MeetingLIatDetail/MeetingLIat?price=' + price + '&roomId=' + that.data.roomId + '&dateCurrentStr=' + that.data.dateCurrentStr,
    })
  },
  enterOrder() {
    wx.navigateTo({
      url: '../../../packageA/pages/MeetingOrderlist/MeetingOrderlist',
    })
  },
})